<template>
    <div class="sms-box">
        <!-- 短信登录组件 -->
        <el-form
            ref="ruleFormRef"
            :model="loginForm"
            status-icon
            :rules="rules"
            label-width="60px"
            class="demo-ruleForm"
        >
            <el-form-item label="手机号" prop="phone">
                <el-input v-model.number="loginForm.phone" placeholder="请输入注册手机号码" autocomplete="off" />
            </el-form-item>
            <el-form-item label="验证码" prop="code">
                <el-input v-model.number="loginForm.code" placeholder="请输入短信验证码" autocomplete="off" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)">登录</el-button>
                <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
import {ref, reactive} from 'vue'
const ruleFormRef = ref()
const loginForm = reactive({
    phone: '',
    code: '',
})
const validatePhone = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请输入有效的手机号'))
    } else {
        if (loginForm.phone !== '') {
            if (!ruleFormRef.value) return ruleFormRef.value.validateField('phone', () => null)
        }
        callback()
    }
}
const checkCode = (ruley, value, callback) => {
    if (!value) {
        return callback(new Error('请输入有效的验证码'))
    }
    setTimeout(() => {
        if (!Number.isInteger(value)) {
            callback(new Error('验证码格式错误,请重新输入'))
        }
        callback()
    }, 500)
}
// rules放在后面，validatePhone、checkCode初始化
const rules = reactive({
    phone: [{ validator: validatePhone, trigger: 'blur' }],
    code: [{ validator: checkCode, trigger: 'blur' }]
})
// 提交
const submitForm = (formEl) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            ElMessage.success('suscerer')
            console.log('submit!')
        } else {
            console.log('error submit!')
            return false
        }
    })
}

const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
}
</script>

<style lang="less" scoped>
.sms-box{
    width: 100%;
    height: 100%;
    margin-top: 20px;
    .demo-ruleForm{
        .el-input{
            width: 90%;
        }
    }
}
</style>